package com.atzxh.guigu.juc.lock;

import java.util.concurrent.locks.ReentrantLock;

public class LockSaleTicket {
    public static void main(String[] args) {
        LTicket lTicket = new LTicket();
        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                lTicket.sale();
            }
        },"aa").start();
        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                lTicket.sale();
            }
        },"bb").start();
        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                lTicket.sale();
            }
        },"cc").start();
    }
}
class LTicket {
    private int num = 30;

    public final ReentrantLock lock = new ReentrantLock(true);

    public void sale() {

        try {
            // 上锁
            lock.lock();
            // 判断是否有票
            if (num > 0) {
                num--;
                System.out.println(Thread.currentThread().getName() + ": 卖出 :" + (30 - num) + "，剩余：" + num + "张票");
            } else {
                System.out.println("票已售空");
            }
        } finally {
            // 解锁
            lock.unlock();
        }
    }
}
